package ac.beiwo.baas.user.controller;

import ac.beiwo.baas.common.entity.SimpleError;
import ac.beiwo.baas.common.entity.SimpleResult;
import ac.beiwo.baas.common.service.MasterService;
import ac.beiwo.baas.user.entity.BaasUser;
import ac.beiwo.baas.user.service.UserService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by Staryet on 15/8/13.
 */
@RestController
@RequestMapping(value = "/user")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private MasterService masterService;
    @Autowired
    private HttpServletRequest request;

    /**
     * 注册用户
     *
     * @param body
     * @return
     * @throws SimpleError
     */
    @RequestMapping(value = "/", method = RequestMethod.POST)
    @ResponseBody
    public SimpleResult register(@RequestBody String body) throws SimpleError {
        JSONObject json = (JSONObject) JSON.parse(body);
        BaasUser user = new BaasUser(json);
        String id = userService.register(user);
        SimpleResult result = SimpleResult.success();
        result.putData("id", id);
        return result;
    }

    /**
     * 更新用户信息
     *
     * @param body
     * @return
     * @throws SimpleError
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.PUT)
    @ResponseBody
    public SimpleResult update(@RequestBody String body, @PathVariable String id) throws SimpleError {
        JSONObject json = (JSONObject) JSON.parse(body);
        BaasUser user = new BaasUser(json);
        //处理权限
        boolean isMaster = masterService.isMaster(request);
        BaasUser currentUser = userService.getCurrentUser(request);
        userService.update(id, user, currentUser, isMaster);
        return SimpleResult.success();
    }

    /**
     * 用户登录
     *
     * @param username
     * @param password
     * @return
     * @throws SimpleError
     */
    @RequestMapping(value = "/login", method = RequestMethod.GET)
    @ResponseBody
    public BaasUser login(@RequestParam(required = true) String username, @RequestParam(required = true) String password) throws SimpleError {
        return userService.login(username, password);
    }

}
